'use client';
import React, { useState, useMemo } from 'react';
import { Search, Plus, Filter } from 'lucide-react';
import { KnowledgeBase } from './types';
import {
  mockKnowledgeBases,
  mockUserInfo,
  getPlatformStats,
} from './constants/mockData';
import KnowledgeCard from './KnowledgeCard';
import KnowledgeCreatingModal from './KnowledgeCreatingModal';
import ShopKnowledgeDropdown from './ShopKnowledgeDropdown';
import DatasetDetailPage from './DatasetDetailPage';

const RAGKnowledgePage: React.FC = () => {
  const [searchString, setSearchString] = useState('');
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [creatingLoading, setCreatingLoading] = useState(false);
  const [knowledgeList, setKnowledgeList] =
    useState<KnowledgeBase[]>(mockKnowledgeBases);
  const [selectedKnowledgeBase, setSelectedKnowledgeBase] =
    useState<KnowledgeBase | null>(null);
  const [selectedPlatform, setSelectedPlatform] = useState<string>('all');

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchString(e.target.value);
  };

  const showModal = () => {
    setVisible(true);
  };

  const hideModal = () => {
    setVisible(false);
  };

  const onCreateOk = async (name: string, description = '') => {
    setCreatingLoading(true);
    setTimeout(() => {
      const newKB: KnowledgeBase = {
        id: `kb_${Date.now()}`,
        name,
        description,
        doc_num: 0,
        avatar: '',
        nickname: mockUserInfo.nickname,
        permission: 'private',
        update_time:
          new Date().toLocaleDateString('en-GB') +
          ' ' +
          new Date().toLocaleTimeString('en-GB', { hour12: false }),
        create_time: new Date().toISOString(),
      };
      setKnowledgeList((prev) => [newKB, ...prev]);
      setCreatingLoading(false);
      hideModal();
    }, 1000);
  };

  const handleCardClick = (knowledgeBase: KnowledgeBase) => {
    setSelectedKnowledgeBase(knowledgeBase);
  };

  const handleDeleteKnowledge = (knowledgeBaseId: string) => {
    setKnowledgeList((prev) => prev.filter((kb) => kb.id !== knowledgeBaseId));
  };

  const handleBackToList = () => {
    setSelectedKnowledgeBase(null);
  };

  const filteredList = useMemo(() => {
    return knowledgeList.filter((item) => {
      const matchesSearch =
        item.name.toLowerCase().includes(searchString.toLowerCase()) ||
        item.description.toLowerCase().includes(searchString.toLowerCase());
      const matchesPlatform =
        selectedPlatform === 'all' ||
        (selectedPlatform === 'other' && !item.platform) ||
        item.platform === selectedPlatform;
      return matchesSearch && matchesPlatform;
    });
  }, [knowledgeList, searchString, selectedPlatform]);

  const platformStats = useMemo(() => getPlatformStats(), [knowledgeList]);

  // 平台过滤选项
  const platformOptions = [
    { value: 'all', label: '全部平台', count: knowledgeList.length },
    { value: 'taobao', label: '淘宝', count: platformStats.taobao || 0 },
    { value: 'tmall', label: '天猫', count: platformStats.tmall || 0 },
    { value: 'pdd', label: '拼多多', count: platformStats.pdd || 0 },
    { value: 'jd', label: '京东', count: platformStats.jd || 0 },
    { value: 'douyin', label: '抖音', count: platformStats.douyin || 0 },
    {
      value: 'xiaohongshu',
      label: '小红书',
      count: platformStats.xiaohongshu || 0,
    },
    { value: 'other', label: '其他', count: platformStats.other || 0 },
  ].filter((option) => option.count > 0 || option.value === 'all');

  // 如果选择了知识库，显示详情页面
  if (selectedKnowledgeBase) {
    return (
      <DatasetDetailPage
        knowledgeBase={selectedKnowledgeBase}
        onBack={handleBackToList}
      />
    );
  }

  // 默认显示知识库列表
  return (
    <div className="flex flex-col flex-1 py-12 overflow-auto bg-gray-50 min-h-screen">
      {/* 顶部区域 */}
      <div className="flex justify-between items-start px-15 mb-8">
        <div>
          <h1 className="text-3xl font-semibold leading-10 text-blue-600 mb-2">
            欢迎回来, {mockUserInfo.nickname}
          </h1>
          <p className="text-base font-normal leading-6 text-gray-600">
            今天您要使用哪个知识库呢？
          </p>
          <div className="mt-3 flex gap-4 text-sm text-gray-500">
            <span>共 {knowledgeList.length} 个知识库</span>
            <span>已筛选 {filteredList.length} 个</span>
          </div>
        </div>
        <div className="flex items-center gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="搜索知识库名称或描述"
              value={searchString}
              onChange={handleInputChange}
              className="w-64 pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>
          <button
            onClick={showModal}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-semibold"
          >
            <Plus className="w-4 h-4" />
            创建知识库
          </button>
          <ShopKnowledgeDropdown />
        </div>
      </div>

      {/* 平台过滤器 */}
      <div className="px-15 mb-6">
        <div className="flex items-center gap-2 mb-4">
          <Filter className="w-4 h-4 text-gray-500" />
          <span className="text-sm font-medium text-gray-700">按平台筛选:</span>
        </div>
        <div className="flex flex-wrap gap-2">
          {platformOptions.map((option) => (
            <button
              key={option.value}
              onClick={() => setSelectedPlatform(option.value)}
              className={`px-3 py-1.5 rounded-full text-sm font-medium transition-all duration-200 ${
                selectedPlatform === option.value
                  ? 'bg-blue-600 text-white shadow-md'
                  : 'bg-white text-gray-600 border border-gray-200 hover:bg-gray-50'
              }`}
            >
              {option.label}
              <span className="ml-1 text-xs opacity-75">({option.count})</span>
            </button>
          ))}
        </div>
      </div>

      {/* 加载状态 */}
      {loading && (
        <div className="flex justify-center py-8">
          <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
        </div>
      )}

      {/* 知识库列表 */}
      <div className="px-15 overflow-auto">
        <div>
          <div className="flex flex-wrap gap-6 pt-1">
            {filteredList?.length > 0 ? (
              filteredList.map((item, index) => (
                <KnowledgeCard
                  item={item}
                  key={`${item?.name}-${index}`}
                  onCardClick={handleCardClick}
                  onDelete={handleDeleteKnowledge}
                />
              ))
            ) : (
              <div className="w-full flex flex-col items-center justify-center py-16 text-gray-500">
                <div className="text-center">
                  <p className="text-lg font-medium mb-2">
                    {searchString || selectedPlatform !== 'all'
                      ? '没有找到匹配的知识库 🔍'
                      : '还没有知识库，创建一个开始吧！ 🚀'}
                  </p>
                  {(searchString || selectedPlatform !== 'all') && (
                    <button
                      onClick={() => {
                        setSearchString('');
                        setSelectedPlatform('all');
                      }}
                      className="mt-2 text-blue-600 hover:text-blue-700 text-sm underline"
                    >
                      清除筛选条件
                    </button>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* 底部提示 - 移除border */}
          {filteredList.length > 0 && (
            <div className="text-center py-6 text-gray-500 mt-6">
              就这些了，没有更多了。😊
            </div>
          )}
        </div>
      </div>

      {/* 创建知识库模态框 */}
      <KnowledgeCreatingModal
        loading={creatingLoading}
        visible={visible}
        hideModal={hideModal}
        onOk={onCreateOk}
      />
    </div>
  );
};

export default RAGKnowledgePage;
